﻿using Magicodes.ExporterAndImporter.Excel;
using PHMEE.EnergyEfficiency.Fuel;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace PHMEE.EnergyEfficiency
{
    /// <summary>
    /// 流量计导出Excel
    /// </summary>
    public class FlowmeterExportAppService : PHMEEAppService, IFlowmeterExportAppService
    {
        private readonly IExcelExporter _excelExporter;
        private readonly IMassFlowMeterRepository _iMassFlowMeterRepository;


        public FlowmeterExportAppService(IExcelExporter excelExporter, IMassFlowMeterRepository iMassFlowMeterRepository)
        {
            _excelExporter = excelExporter;
            _iMassFlowMeterRepository = iMassFlowMeterRepository;
        }

        /// <summary>
        /// 导出日期范围内每个流量计的数据
        /// </summary>
        /// <param name="vesselId">船舶ID</param>
        /// <param name="startDate">开始日期</param>
        /// <param name="endDate">结束日期</param>
        /// <returns></returns>
        public async Task<byte[]> GenerateFlowmeterSheetsExcelAsync(Guid vesselId, DateTime startDate, DateTime endDate)
        {
            var timer = QueryDateTimeUtils.ProcessForDateRangeBeforeTodayQuery(startDate, endDate);

            var flowmeterDict = await _iMassFlowMeterRepository.GetFlowmeterByDateAsync(vesselId, timer.startDateTime, timer.endDateTime);

            var exporter = new ExcelExporter();

            bool firstSheet = true;

            foreach (var kvp in flowmeterDict)
            {
                if (!firstSheet)
                {
                    exporter.SeparateBySheet();
                }
                firstSheet = false;

                var dtoList = ObjectMapper.Map<List<MassFlowmeter>, List<MassFlowmeterExcelDto>>(kvp.Value);

                exporter.Append(dtoList, kvp.Key);
            }

            var excelBytes = await exporter.ExportAppendDataAsByteArray();

            return excelBytes;
        }
    }
}
